package cn.tedu.crm.dictoption.service.impl;

import cn.tedu.crm.base.exception.ServiceException;
import cn.tedu.crm.base.response.StatusCode;
import cn.tedu.crm.dict.mapper.DictMapper;
import cn.tedu.crm.dict.pojo.dto.DictQuery;
import cn.tedu.crm.dict.pojo.vo.DictVO;
import cn.tedu.crm.dictoption.mapper.DictOptionMapper;
import cn.tedu.crm.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.crm.dictoption.pojo.dto.DictOptionSaveParam;
import cn.tedu.crm.dictoption.pojo.entity.DictOption;
import cn.tedu.crm.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.crm.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    DictOptionMapper dictOptionMapper;
    @Autowired
    DictMapper dictMapper;


    @Override
    public List<DictOptionVO> selectDictOption(DictOptionQuery dictOptionQuery) {
        log.debug("查询字典项业务：{}",dictOptionQuery);
        List<DictOptionVO> list = dictOptionMapper.selectDictOption(dictOptionQuery);
        return list;
    }

    @Override
    public void saveDictOption(DictOptionSaveParam dictOptionSaveParam) {
        log.debug("保存字典项业务：{}",dictOptionSaveParam);
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionSaveParam,dictOption);
        if(dictOption.getId() == null){
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insert(dictOption);
        }else{
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.updateDictOption(dictOption);
        }
    }

    @Override
    public void deleteDictOption(Long id) {
        log.debug("删除字典项业务：{}",id);
        dictOptionMapper.deleteDictOption(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        log.debug("根据字典code查询所有字典项业务：{}",code);
        //需要根据字典code将对应的字典VO查出来
        DictQuery dictQuery = new DictQuery();
        dictQuery.setCode(code);
        List<DictVO> dictVOList = dictMapper.selectDict(dictQuery);
        //log.debug("根据字典code查询所有字典项业务：参数{}",dictQuery.getCode());
        //若查询结果正常,取出此字典id,方便下一步查询
        if(dictVOList!=null && dictVOList.size()>0){
            DictVO dictVO = dictVOList.get(0);
            //封装字典项查询对象
            DictOptionQuery dictOptionQuery = new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            //查询字典项
            List<DictOptionVO> dictOptionVOList = dictOptionMapper.selectDictOption(dictOptionQuery);
            //log.debug("返回参数{}",dictOptionVOList);
            return dictOptionVOList;

        }else{
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
    }
}
